/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iplayer;

import com.sun.javafx.functions.Function0;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javafx.async.RunnableFuture;

/**
 *
 * @author stephengalbraith
 */
public class AsyncGetIplayerRecord implements RunnableFuture {

    private Program program;
    private String[] mode;
    private String get_iplayer;
    private String flvstreamer;
    private String ffmpeg;
    private String output;
    private final LateReturnable setter;

    public AsyncGetIplayerRecord(LateReturnable setter, Program program, String get_iplayer, String flvstreamer, String ffmpeg, String output, String[] modes) {
        this.program = program;
        this.mode = modes;
        this.get_iplayer = get_iplayer;
        this.flvstreamer = flvstreamer;
        this.ffmpeg = ffmpeg;
        this.output = output;
        this.setter = setter;

    }

    public void run() {
        // for debug.. dummy download
        if (false) {
            for (int i = 0; i < 100; i++) {
                final int percent = i;
                javafx.lang.FX.deferAction(new Function0<Void>() {

                    public Void invoke() {
                        AsyncGetIplayerRecord.this.setter.setValue(Double.valueOf(percent));
                        return null;
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    // ignore
                    }
            }
            return;
        }
        try {
            String modes = "";
            if (null != this.mode) {
                for (int i = 0; i < this.mode.length; i++) {
                    modes += this.mode[i] + ((i == this.mode.length - 1) ? "" : ",");
                }
            }
            System.out.println(modes);
            String[] args = new String[11];
            args[0] = this.get_iplayer;
            args[1] = "--flvstreamer";
            args[2] = this.flvstreamer;
            args[3] = "--ffmpeg";
            args[4] = this.ffmpeg;
            args[5] = "--output";
            args[6] = this.output;
            args[7] = "--modes";
            args[8] = modes;
            args[9] = "--pid";
            args[10] = this.program.pid;
            System.out.println(args[0] + " " + args[1] + " " + args[2] + " " + args[3] + " " + args[4] + " " + args[5] + " " + args[6] + " " + args[7] + " " + args[8] + " " + args[9] + " " + args[10] + " ");
            final Process process = Runtime.getRuntime().exec(args);
//            final InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
            final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());
//            BufferedReader buf = new BufferedReader(inputStreamReader);
            BufferedReader errBuf = new BufferedReader(errorStreamReader);
            String line = "";

            boolean isIphone = false;
            int character = 0;
            StringBuffer percent = new StringBuffer();
            boolean readPercent = false;
            while (character != -1) {
//                character = buf.read();
//                System.out.print( (char)character);
                character = errBuf.read();
//                System.out.print( (char)character);
                if ('(' == (char) character) {
                    percent = new StringBuffer();
                    readPercent = true;
                }
                if ('%' == (char) character) {
                    readPercent = false;

                    final String percentString = percent.toString();
                    //System.out.println(percentString);
                    javafx.lang.FX.deferAction(new Function0<Void>() {

                        public Void invoke() {
                            Double progress = null;
                            try {
                                progress = Double.valueOf(percentString);
                            } catch (NumberFormatException error) {
                                // just ignore..
                            }
                            if (null != progress) {
                                AsyncGetIplayerRecord.this.setter.setValue(progress);
                            }
                            return null;
                        }
                    });

                }

                if (readPercent) {
                    if ('(' != (char) character) {
                        percent.append((char) character);
                    }
                }
            }

            System.out.println("FINISHED RECORDING");
//            buf.close();
            errBuf.close();
//            inputStreamReader.close();
            errorStreamReader.close();
            process.getInputStream().close();
        } catch (Exception e) {
            // never
            e.printStackTrace();
        }
    }
}
